/*
Copyright IBM Corp. 2016 All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package factory

import (
	"blockchain/bccsp"
	"blockchain/bccsp/sw"
	"github.com/pkg/errors"
)

const (
	// SW名字
	SoftwareBasedFactoryName = "SW"
)

// 软件实现的 Facotory
type SWFactory struct{}

func (f *SWFactory) Name() string {
	return SoftwareBasedFactoryName
}

// 使用config 得到SWFactory
func (f *SWFactory) Get(config *FactoryOpts) (bccsp.BCCSP, error) {
	//验证参数
	if config == nil || config.SW == nil {
		return nil, errors.New("Invalid config. It must not be nil.")
	}

	swOpts := config.SW

	var ks bccsp.KeyStore
	switch {
	case swOpts.FileKeystore != nil:
		// 初始化存储KeyStore
		fks, err := sw.NewFileBasedKeyStore(nil, swOpts.FileKeystore.KeyStorePath, false)
		if err != nil {
			return nil, errors.Wrapf(err, "Failed to initialize software key store")
		}
		ks = fks
	default:
		// 默认使用dummyKeyStore
		ks = sw.NewDummyKeyStore()
	}

	return sw.NewWithParams(swOpts.Security, swOpts.Hash, ks)
}

// sw配置包含产生swFactory的各种配置选项
type SwOpts struct {
	Security     int               `json:"security" yaml:"Security"`                             //ECD的安全位数
	Hash         string            `json:"hash" yaml:"Hash"`                                     // 指定的hash函数
	FileKeystore *FileKeystoreOpts `json:"filekeystore,omitempty" yaml:"FileKeyStore,omitempty"` //存储
}

// FileKey的store opts
type FileKeystoreOpts struct {
	KeyStorePath string `yaml:"KeyStore"`
}
